package com.quxue.im.service.impl;

import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.quxue.im.common.Const;
import com.quxue.im.common.enums.ApplySourceEnum;
import com.quxue.im.entity.ChatApply;
import com.quxue.im.entity.ChatFriend;
import com.quxue.im.entity.ChatUser;
import com.quxue.im.exception.LogicException;
import com.quxue.im.mapper.ChatFriendMapper;
import com.quxue.im.mapper.ChatUserMapper;
import com.quxue.im.req.friend.BlackReq;
import com.quxue.im.req.friend.DelFriendReq;
import com.quxue.im.req.friend.RemarkReq;
import com.quxue.im.req.friend.TopReq;
import com.quxue.im.service.IChatFriendService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.quxue.im.service.IChatUserService;
import com.quxue.im.vo.friend.FriendVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 好友表 服务实现类
 * </p>
 *
 * @author jinken
 * @since 2023-11-10
 */
@Service
public class ChatFriendServiceImpl extends ServiceImpl<ChatFriendMapper, ChatFriend> implements IChatFriendService {

    @Resource
    private IChatUserService chatUserService;


    @Resource
    private ChatUserMapper chatUserMapper;

    @Override
    public List<FriendVo> friendList() {
        //获取当前登录用户ID
        long userId = StpUtil.getLoginIdAsLong();
        List<FriendVo> list = baseMapper.selectFriend(userId);
        return list;
    }

    @Override
    public FriendVo getFriendInfo(Long friendId) {

        //1.当前登录用户id
        long userId = StpUtil.getLoginIdAsLong();
        //2. 查询当前登录用户指定的好友信息
        FriendVo friend = baseMapper.selectFriendInfo(userId,friendId);

        return friend;
    }

    @Override
    public FriendVo findFriend(String param) {
        /**
         * 处理步骤
         * 不能添加好友
         * 1，没有搜索到账号
         * 2，自己
         */

        QueryWrapper<ChatUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone",param);
        queryWrapper.or();
        queryWrapper.eq("chat_no",param);
        ChatUser chatUser = chatUserService.getOne(queryWrapper);

        if(Objects.isNull(chatUser)){
            throw new LogicException("暂无结果");
        }else if(chatUser.getUserId()==StpUtil.getLoginIdAsLong()){
            throw new LogicException("不能添加自己为好友");
        }

        FriendVo friendVo = new FriendVo();
        if(Validator.isMobile(param)){
            friendVo.setSource(ApplySourceEnum.PHONE);
        }else{
            friendVo.setSource(ApplySourceEnum.CHAT_NO);
        }
        BeanUtil.copyProperties(chatUser,friendVo);

        //去好友列表查询一下是否是好友，是否加入了黑名单等
        //1.当前登录用户id
        long userId = StpUtil.getLoginIdAsLong();
        //2. 查询当前登录用户指定的好友信息
        FriendVo friend = baseMapper.selectFriendInfo(userId,Long.valueOf(friendVo.getUserId()));

        if(Objects.nonNull(friend)){
            //已经是好友
            friendVo.setIsFriend(Const.YES);
            //是否拉入了黑名单
            friendVo.setBlack(friend.getBlack());
        }else{
            friendVo.setIsFriend(Const.NO);
        }


        return friendVo;
    }

    @Override
    public void addFriend(ChatApply chatApply) {
        //申请人信息
        ChatUser fromUser = chatUserMapper.selectById(chatApply.getFromId());
        //被申请人信息
        ChatUser toUser = chatUserMapper.selectById(chatApply.getToId());

        Long fromId = chatApply.getFromId();
        Long toId = chatApply.getToId();
        LocalDateTime now = LocalDateTime.now();
        String source = chatApply.getApplySource();

        ChatFriend friendOne = new ChatFriend();
        friendOne.setId(IdUtil.getSnowflakeNextId());
        friendOne.setFromId(fromId);
        friendOne.setToId(toId);
        friendOne.setCreateTime(now);
        //将来源和昵称好友信息中
        friendOne.setSource(source);
        //设置好友备注（默认用户的昵称）
        friendOne.setRemark(toUser.getNickName());

        ChatFriend friendTwo = new ChatFriend();
        friendTwo.setId(IdUtil.getSnowflakeNextId());
        friendTwo.setFromId(toId);
        friendTwo.setToId(fromId);
        friendTwo.setCreateTime(now);
        //将来源和昵称好友信息中
        friendTwo.setSource(source);
        //设置好友备注（默认用户的昵称）
        friendTwo.setRemark(fromUser.getNickName());


        //批量添加好友
        this.saveBatch(Arrays.asList(friendOne,friendTwo));
    }

    @Override
    public void remark(RemarkReq remarkReq) {
        UpdateWrapper<ChatFriend> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("from_id",StpUtil.getLoginIdAsLong());
        updateWrapper.eq("to_id",remarkReq.getUserId());

        updateWrapper.set("remark",remarkReq.getRemark());
        this.update(updateWrapper);
    }

    @Override
    public void black(BlackReq blackReq) {
        UpdateWrapper<ChatFriend> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("from_id",StpUtil.getLoginIdAsLong());
        updateWrapper.eq("to_id",blackReq.getUserId());
        updateWrapper.set("black",blackReq.getBlack());
        this.update(updateWrapper);
    }

    @Override
    public void delFriend(DelFriendReq delFriendReq) {
        /**
         * 删除好友为单向删除
         */
        UpdateWrapper<ChatFriend> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("from_id",StpUtil.getLoginIdAsLong());
        updateWrapper.eq("to_id",delFriendReq.getUserId());
        this.remove(updateWrapper);
    }

    @Override
    public void top(TopReq topReq) {
        UpdateWrapper<ChatFriend> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("from_id",StpUtil.getLoginIdAsLong());
        updateWrapper.eq("to_id",topReq.getUserId());
        updateWrapper.set("top",topReq.getTop());
        this.update(updateWrapper);
    }
}
